package com.example.flux.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebHandler;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

@Controller
@RequestMapping("/test")
public class TestController {

    @Autowired
    WebHandler webHandler;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @GetMapping("/t")
    public String test() {
        logger.debug("logger test");
        logger.info("/t start");
        String str = getStr();
        logger.info("/t end");
        return str;

    }

    @GetMapping("/t1")
    public Mono<Void> test2(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        DataBuffer dataBuffer = response.bufferFactory().allocateBuffer();
        dataBuffer.write("hello word".getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }

    @GetMapping(path = "/t2")
    public Flux<String> test3() {
        logger.info("test3 start");
        Flux<String> stringFlux = Flux.fromStream(IntStream.range(0, 100).mapToObj(value -> {
                    logger.info("test3" + value);
                    try {
                        TimeUnit.MILLISECONDS.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return "flux -- >" + value;
                }
        ));
        logger.info("test3 end");
        return stringFlux;
    }

    private String getStr() {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "hell webFlux";
    }
}
